import { Button } from "antd";
import { useState } from "react";
import { flushSync } from "react-dom";

interface Props {
  title: string;
}
const HooksDemo = (props: Props) => {
  // useState 钩子函数，用于定义状态和更新状态的函数
  // 参数是初始状态
  // 返回值是一个数组，第一个元素是当前的状态值，第二个元素是更新状态的函数
  // 每次调用更新状态的函数，都会重新渲染组件

  // //useState 自带了性能优化，只有在状态改变时才会重新渲染组件
  console.log(props);
  console.log("视图渲染了！");
  const [num, setNum] = useState(0 as number);
  const [obj, setObj] = useState({
    name: "张三",
    age: 18,
    gender: "男",
  });
  const add = () => {
    for (let i = 0; i < 10; i++) {
      flushSync(() => {
        setNum(num + 1);
        // setNum((prevNum) => prevNum + 1);
      });
    }
  };

  return (
    <>
      <div>{num}</div>
      <br />
      <Button onClick={add}>增加</Button>
      <br />
      <div>{obj.name}</div>
      <div>{obj.age}</div>
      <div>{obj.gender}</div>
      <Button onClick={() => setObj({ ...obj, age: obj.age + 1 })}>
        增加年龄
      </Button>
    </>
  );
};

export default HooksDemo as React.FC;
